package com.ruoyi.crm.service.impl;

import java.util.Date;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.Seq;
import com.ruoyi.crm.domain.*;
import com.ruoyi.crm.domain.vo.ContractVo;
import com.ruoyi.crm.mapper.*;
import com.ruoyi.crm.moulds.mq.CrmProducer;
import com.ruoyi.crm.service.BizException;
import com.ruoyi.crm.service.IAssignRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.crm.service.IBusinessService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 商机Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-03-13
 */
@Service
public class BusinessServiceImpl implements IBusinessService 
{
    @Resource
    private BusinessMapper businessMapper;

    @Resource
    private CourseMapper courseMapper;
    @Resource
    private ContractMapper contractMapper;
    @Resource
    private AssignRecordMapper assignRecordMapper;
    @Resource
    private IAssignRecordService assignRecordService;
   @Resource
   private ActivityMapper activityMapper;

   @Resource
   private CrmProducer crmProducer;

    /**
     * 查询商机
     * 
     * @param id 商机主键
     * @return 商机
     */
    @Override
    public Business selectBusinessById(Long id)
    {
        return businessMapper.selectBusinessById(id);
    }

    /**
     * 查询商机列表
     * 
     * @param business 商机
     * @return 商机
     */
    @Override
    public List<Business> selectBusinessList(Business business)
    {
        return businessMapper.selectBusinessList(business);
    }

    /**
     * 新增商机
     * 
     * @param business 商机
     * @return 结果
     */
    @Override
    public int insertBusiness(Business business)
    {
        business.setCreateBy(SecurityUtils.getUsername());
        business.setCreateTime(DateUtils.getNowDate());
        return businessMapper.insertBusiness(business);
    }

    /**
     * 修改商机
     * 
     * @param business 商机
     * @return 结果
     */
    @Override
    public int updateBusiness(Business business)
    {
        return businessMapper.updateBusiness(business);
    }

    /**
     * 批量删除商机
     * 
     * @param ids 需要删除的商机主键
     * @return 结果
     */
    @Override
    public int deleteBusinessByIds(Long[] ids)
    {
        return businessMapper.deleteBusinessByIds(ids);
    }

    /**
     * 删除商机信息
     * 
     * @param id 商机主键
     * @return 结果
     */
    @Override
    public int deleteBusinessById(Long id)
    {
        return businessMapper.deleteBusinessById(id);
    }


    /*踢回公海
    * 1、商机状态改为 踢回公海
    * 2、分配记录状态latest改为0
    * */
    @Override
    @Transactional
    public int giveBck(Long id) {
        assignRecordMapper.updateLates(id,"0", AssignRecord.Type.BUSINESS.getValue());
        Business business=businessMapper.selectBusinessById(id);
        business.setStatus(Clue.Status.FAKE.getValue());
        return businessMapper.updateBusiness(business);
    }

    @Override
    public int reset(Long id) {
        AssignRecord assignRecord=new AssignRecord();
        assignRecord.setUserName(SecurityUtils.getUsername());
        assignRecord.setAssignId(id);
        assignRecord.setUserId(SecurityUtils.getUserId());
        assignRecord.setType(AssignRecord.Type.BUSINESS.name());
        assignRecord.setUpdateTime(new Date());
        return assignRecordService.insertAssignRecord(assignRecord);
    }

    @Override
    @Transactional
    public int transformCustomer(ContractVo vo) {
        //更新商机状态
        Business business=businessMapper.selectBusinessById(vo.getId());
        if(business.getCourseId()==null){
            throw new BizException("商机里面没有选择课程，无法转换成客户");
        }
        if(contractMapper.selectContranByNo(vo.getContractNo())!=null){
            throw new BizException("合同编号已存在，无法转成客户");
        }
        business.setStatus(Clue.Status.TO_CUSTOMER.getValue());
        business.setUpdateBy(SecurityUtils.getUsername());
        business.setUpdateTime(new Date());
        businessMapper.updateBusiness(business);

        //插入合同
        Contract contract=new Contract();
        BeanUtils.copyProperties(business,contract);
        contract.setBusinessId(vo.getId());
        contract.setContractNo(vo.getContractNo());
        contract.setFileName(vo.getFileName());
        contract.setPhone(vo.getPhone());
        Course course = courseMapper.selectCourseById(business.getCourseId());
        contract.setCourseName(course.getName());
        //随机生产id
        String businessKey= Seq.getId();
        contract.setId(businessKey);
        contract.setCreateBy(SecurityUtils.getUsername());
        contract.setCreateTime(DateUtils.getNowDate());

        contract.setDeptId(SecurityUtils.getDeptId());
        contract.setStatus("4"); //状态 待审核1 已通过2 已驳回3 全部完成4
        contract.setEmail(vo.getEmail());
        //计算参加活动后的金额
        setContractOrder(contract);
        contractMapper.insertContract(contract);
            //通过邮件或短信发送消息给用户
         crmProducer.produceContractCreatedMessage(contract);
         return 1;
    }

    private void setContractOrder(Contract contract) {
        Course course=courseMapper.selectCourseById(contract.getCourseId());
        Activity activity=null;
        if(contract.getActivityId()!=null){
            activity=activityMapper.selectActivityById(contract.getActivityId());
        }

        if(activity==null){
            contract.setContractOrder(course.getPrice());
        }else {
            if("1".equals(activity.getType())){
                contract.setDiscountType("课程折扣");
                contract.setContractOrder(Double.valueOf(activity.getDiscount()/10.0*course.getPrice()));
            }else {
                contract.setDiscountType("代金券");
                contract.setContractOrder(course.getPrice()-activity.getVouchers());
            }
        }
    }
}
